//
//  HMTextView.swift
//  MyWeibo
//
//  Created by apple on 16/4/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class HMTextView: UITextView {
    
    //提供给外界的占位文字属性
    var placeholder: String? {
        
        //加载完毕后设置占位符
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
    // 外界设置了当前textView的字体的话，需要将占位文字的字体一并设置
   override var font:UIFont?{
        
        didSet{
            
            placeholderLabel.font = font
            
        }
        
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置ui
    func setupUI(){
        
        //添加控件
        addSubview(placeholderLabel)
        
        
        //设置控件约束
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(5)
            make.top.equalTo(8)
            make.width.equalTo(self).offset(-10)
            
        }
        
        //发送通知监听textView值得改变  来告诉键盘弹出与否
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChage", name: UITextViewTextDidChangeNotification, object: nil)
 
    }
    
    
    //创建一个占位符隐藏与消失的监听方法
    @objc private func textDidChage(){
        
        placeholderLabel.hidden = hasText()
    }
    
    
    //懒加载占位符
    private lazy var placeholderLabel:UILabel = {
        
        //创建一个label
        let label = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 12)
        //设置文字
        label.text = "喂 妖妖灵嘛  这里有人装逼 场面控制不住了~~"
        //设置换行
        label.numberOfLines = 0
        return label
    }()
    
    deinit{
        //调用系统的通知 移除
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
}
